import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '@/components/Home.vue'
import storage from '../utils/storage'
import utils from '../utils/utils'
import api from '../api'

const routes = [
    {
        name: 'home',
        path: '/',
        meta: {
            title: '首页'
        },
        component: Home,
        redirect: '/welcome',
        children: [
            {
                name: 'welcome',
                path: '/welcome',
                meta: {
                    title: '欢迎来到quarkus微服务后台'
                },
                component: () => import('@/views/Welcome.vue')
            },
        ]
    },
    {
        name: 'login',
        path: '/login',
        meta: {
            title: '登录'
        },
        component: () => import('@/views/Login.vue')
    },
    {
        name: '404',
        path: '/404',
        meta: {
            title: '页面不存在'
        },
        component: () => import('@/views/404.vue')
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

async function loadRouters(){
   let userInfo = storage.getItem('userInfo') || {}
   if(userInfo.token){
    const {code,result,message} = await api.menuTreeForUser(userInfo.id)
    let routers = utils.generateRoute(result);
    routers.map(route => {
        // console.log("route>",route)
        let url = `./../views/${route.parentPath}/${route.component}.vue`
        route.component = () => import(url);
        router.addRoute("home", route);
    })
   }
}
await loadRouters();

export default router